<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品编号" prop="commodityId">
        <el-input v-model="queryParams.commodityId" placeholder="请输入商品编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品名" prop="commodityName">
        <el-input v-model="queryParams.commodityName" placeholder="请输入商品名" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="类型" prop="commodityType">
        <el-select v-model="queryParams.commodityType" placeholder="请选择类型" clearable>
          <el-option v-for="dict in dict.type.super_commodity_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['supermarket:commodity:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['supermarket:commodity:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['supermarket:commodity:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['supermarket:commodity:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="commodityList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品编号" align="center" prop="commodityId" />
      <el-table-column label="商品名" align="center" prop="commodityName" width="150" />

      <el-table-column label="图片" align="center" prop="commodityImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.commodityImage" :width="50" :height="50" />
        </template>
      </el-table-column>

      <el-table-column label="类型" align="center" prop="commodityType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.super_commodity_type" :value="scope.row.commodityType" />
        </template>
      </el-table-column>
      <el-table-column label="单价" align="center" prop="unitPrice" />
      <el-table-column label="进价" align="center" prop="cost" />
      <el-table-column label="规格" align="center" prop="specification" />
      <el-table-column label="库存量" align="center" prop="quantity" />
      <el-table-column label="预警值" align="center" prop="warnValue" />
      <el-table-column label="计划量" align="center" prop="planValue" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['supermarket:commodity:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['supermarket:commodity:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改超市商品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名" prop="commodityName">
          <el-input v-model="form.commodityName" placeholder="请输入商品名" />
        </el-form-item>

        <el-form-item label="图片" prop="commodityImage">
          <image-upload v-model="form.commodityImage" />
        </el-form-item>

        <el-form-item label="类型" prop="commodityType">
          <el-select v-model="form.commodityType" placeholder="请选择类型">
            <el-option v-for="dict in dict.type.super_commodity_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input v-model="form.unitPrice" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="进价" prop="cost">
          <el-input v-model="form.cost" placeholder="请输入进价" />
        </el-form-item>
        <el-form-item label="规格" prop="specification">
          <el-input v-model="form.specification" placeholder="请输入规格" />
        </el-form-item>
        <el-form-item label="库存量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入库存量" :disabled="isBanned" />
        </el-form-item>
        <el-form-item label="预警值" prop="warnValue">
          <el-input v-model="form.warnValue" placeholder="请输入预警值" />
        </el-form-item>
        <el-form-item label="计划量" prop="planValue">
          <el-input v-model="form.planValue" placeholder="请输入计划量" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label
              }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCommodity, getCommodity, delCommodity, addCommodity, updateCommodity } from "@/api/supermarket/commodity";
import ImageUpload from "@/components/ImageUpload/index.vue"
//import { component } from "vue/types/umd";

export default {
  name: "Commodity",
  dicts: ['super_commodity_type', 'sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,

      //修改时禁用表单项
      isBanned: false,


     timer:null,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 超市商品信息表格数据
      commodityList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        commodityId: null,
        commodityName: null,
        commodityType: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        commodityName: [
          { required: true, message: "商品名不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();

    this.timer = window.setInterval(() => {
      setTimeout(() => {
        this.getList() //调用接口的方法
        console.log("定时任务")
      }, 0)
    }, 120000);

  },
  beforeDestroy() {
   clearInterval(this.timer)
  },
  methods: {
    /** 查询超市商品信息列表 */
    getList() {
      this.loading = true;
      listCommodity(this.queryParams).then(response => {
        this.commodityList = response.rows;
        this.total = response.total;
        this.loading = false;
        //console.log(this.commodityList)
        // 遍历commodityList数组中的每个元素
        this.commodityList.forEach(item => {
          // 检查每个元素的quantity和warnValue的大小关系
          if (item.quantity < item.warnValue) {
            this.$modal.notifyWarning(item.commodityName + "库存不足");
          }
          //  console.log(item.quantity + " " + item.warnValue)
        });

      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        commodityId: null,
        commodityName: null,
        commodityType: null,
        unitPrice: null,
        cost: null,
        specification: null,
        quantity: null,
        warnValue: null,
        planValue: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        commodityImage: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.commodityId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加超市商品信息";

      this.isBanned = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const commodityId = row.commodityId || this.ids
      this.isBanned = true;

      getCommodity(commodityId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改超市商品信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          //console.log("1");
          if (this.form.quantity==null||this.form.quantity<0||this.form.cost>this.form.unitPrice) {
            this.$modal.alertError("库存数或进价单价关系不正确！");
            return;
          }
          // if (this.form.warnValue!=null&&(this.form.warnValue < 0 || this.form.warnValue>500000)){
          //   this.$modal.alertError("预警量数据范围不正确！");
          //   return;
          // }
          // if (this.form.remark != null && this.form.remark !="")
          // if (this.form.remark.length > 255 || this.form.commodityName.length < 1 || this.form.commodityName.length>255)
          // {
          //   this.$modal.alertError("备注或商品名长度不正确！");
          //   return;
          // }

          if (this.form.commodityId != null) {
            updateCommodity(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCommodity(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const commodityIds = row.commodityId || this.ids;
      this.$modal.confirm('是否确认删除超市商品信息编号为"' + commodityIds + '"的数据项？').then(function () {
        return delCommodity(commodityIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('supermarket/commodity/export', {
        ...this.queryParams
      }, `commodity_${new Date().getTime()}.xlsx`)
    }

  },

};
</script>
